//
//  FBFuNLoginFriendPickerViewController.m
//  IWISHING
//
//  Created by Phan Ba Minh on 1/24/13.
//  Copyright (c) 2013 kidbaw. All rights reserved.
//

#import "FBFunLoginFriendPickerViewController.h"
#import "FBFunLoginManager.h"
#import "AppViewController.h"
#import "UIImageView+WebCache.h"
#import "SBJSON.h"

@interface FBFunLoginFriendPickerViewController ()

@end

@implementation FBFunLoginFriendPickerViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _APIRequester = [APIRequester new];
        _friendCategory = [[PersonCategoryData alloc] initWithPersonName:@"" andPersonID:@"" andPersonSmallAvatar:nil];
        _pickerCategory = [[PersonCategoryData alloc] initWithPersonName:@"" andPersonID:@"" andPersonSmallAvatar:nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _filterArray = [NSMutableArray new];
    _sortedKeys = [NSMutableArray new];
    _sortedValues = [NSMutableArray new];
    
//    [_tableViewFriendPicker setEditing:YES animated:NO];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[AppViewController Shared] isRequesting:YES andRequestType:ENUM_API_REQUEST_TYPE_FB_GET_FRIENDS andFrame:FRAME(0, HEIGHT_TOOL_BAR, self.view.frame.size.width, self.view.frame.size.height - HEIGHT_TOOL_BAR)];
    
    [_APIRequester requestWithType:ENUM_API_REQUEST_TYPE_FB_GET_FRIENDS andRootURL:[NSString stringWithFormat:@"https://graph.facebook.com/me/friends?access_token=%@", [FBFunLoginManager Shared].accessToken] andPostMethodKind:NO andParams:nil andDelegate:self];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - ROTATION IOS5 & IOS6

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskPortrait;
}

- (BOOL)shouldAutorotate {
    return YES;
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [UIView beginAnimations:nil context:nil];
    
    [[AppViewController Shared] isRequestingAndShouldAutorotateToInterfaceOrientation:toInterfaceOrientation];
    
    [UIView setAnimationDuration:duration];
    [UIView commitAnimations];
}

- (void)viewDidUnload {
    [self setTableViewFriendPicker:nil];
    [self setSearchBarFriendPicker:nil];
    [super viewDidUnload];
}

#pragma mark - APIRequester Protocol
- (void)requestFailed:(ASIHTTPRequest *)request andType:(ENUM_API_REQUEST_TYPE)type
{
    NSLog(@" requestFailed: %@; responseStatusCode: %i ", request.responseString, request.responseStatusCode);
    
    [[AppViewController Shared] isRequesting:NO andRequestType:type andFrame:CGRectZero];
    
    ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_CONNECTION_ERROR);
}
- (void)requestFinished:(ASIHTTPRequest *)request andType:(ENUM_API_REQUEST_TYPE)type
{
    NSLog(@" requestFinished: %@; responseStatusCode: %i ", request.responseString, request.responseStatusCode);
    
    [[AppViewController Shared] isRequesting:NO andRequestType:type andFrame:CGRectZero];
    
    NSError *error;
    SBJSON *sbJSON = [SBJSON new];
    
    if (![sbJSON objectWithString:[request responseString] error:&error] || request.responseStatusCode != 200 || !request) {
//        if (![ASIHTTPRequest isNetworkReachable]) {
//            ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_SERVER_ERROR);
//        }
        ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_SERVER_ERROR);
        return;
    }
    
    if (type == ENUM_API_REQUEST_TYPE_FB_GET_FRIENDS) {
        NSMutableDictionary *jsonData = [sbJSON objectWithString:[request responseString] error:&error];
        if (jsonData) {
            NSMutableArray *dataArray = [jsonData objectForKey:@"data"];
            for (NSMutableDictionary *dic in dataArray) {
                PersonNodeData *node = [[PersonNodeData alloc] initWithPersonName:[dic objectForKey:@"name"] andPersonID:[dic objectForKey:@"id"] andPersonSmallAvatar:nil];
                [_friendCategory addNode:node];
            }
            
            [self searchWithText:@""];
        }
    }
}

#pragma mark - Actions

- (void)hideKeyboard {
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}

- (IBAction)touchBack:(id)sender {
    if ([_delegate respondsToSelector:@selector(didTouchBackFriendPickerCallback)]) {
        [_delegate didTouchBackFriendPickerCallback];
    }
}

- (IBAction)touchDone:(id)sender {
    if ([_delegate respondsToSelector:@selector(didTouchDoneFriendPickerCallback:)]) {
        [_delegate didTouchDoneFriendPickerCallback:_pickerCategory];
    }
}

- (void)searchWithText:(NSString *)text {
    [_sortedKeys removeAllObjects];
    [_sortedValues removeAllObjects];
    
    // CALCULATION
    if (text.length == 0) {
        _filterArray = _friendCategory.categoryArray;
    }
    else {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.personName contains[cd] %@", text];
        _filterArray = (NSMutableArray *)[_friendCategory.categoryArray filteredArrayUsingPredicate:predicate];
    }
    
    NSMutableDictionary *filterDic = [NSMutableDictionary new];
    
    for (PersonNodeData *node in _filterArray) {
        NSString *header = [node.personName substringToIndex:1];
        
        if ([filterDic objectForKey:header]) {
            NSMutableArray *sectionArray = [filterDic objectForKey:header];
            [sectionArray addObject:node];
        }
        else {
//            NSLog(@"header: %@", header);
            NSMutableArray *sectionArray = [NSMutableArray new];
            [sectionArray addObject:node];
            [filterDic setObject:sectionArray forKey:header];
        }
    }
    
    NSArray *sortedKeys = [filterDic.allKeys sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    for (NSString *key in sortedKeys) {
//        NSLog(@"sortedKey: %@", key);
        if ([[filterDic objectForKey:key] count] > 0) {
            [_sortedValues addObject:[filterDic objectForKey:key]];
            [_sortedKeys addObject:key];
        }
    }
    
    [_tableViewFriendPicker reloadData];
}

#pragma mark UITableView Delegate & DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _sortedKeys.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[_sortedValues objectAtIndex:section] count];
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    return nil;
//}

//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//
//    if (section == 6) {
//        UIView *header = [_homeSettingCell loadViewWithType:enumViewType_HomeFotter];
//        return header;
//    }
//    return nil;
//}


//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//    HomeListCellCell *optionView = [[[NSBundle mainBundle] loadNibNamed:@"HomeListCellCell" owner:self options:nil] lastObject];
//    return optionView;
//}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row >= [[_sortedValues objectAtIndex:indexPath.section] count]) {
        return nil;
    }
    
    static NSString *cellID = @"cellID";
    PersonNodeData *node = ((PersonNodeData *)[[_sortedValues objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]);
    
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    
    [cell.imageView setImageWithURL:[NSURL URLWithString:STRING_REQUEST_FB_PICTURE_URL(node.personID)] placeholderImage:IMG_AVARTAR_DUMMY];
    cell.textLabel.text = node.personName;
    cell.textLabel.textAlignment = UITextAlignmentLeft;
    cell.textLabel.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    if ([_pickerCategory.categoryArray indexOfObject:node] < [_pickerCategory.categoryArray count]) {
        NSLog(@"indexOfObject: %i", [_pickerCategory.categoryArray indexOfObject:node]);
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row >= [[_sortedValues objectAtIndex:indexPath.section] count]) {
        return;
    }
    
//    UITableViewCell *oldCell;
//    int count = [[_sectionDictionary.allValues objectAtIndex:indexPath.section] count];
//    
//    for (NSUInteger i = 0; i < count; ++i) {
//        oldCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:indexPath.section]];
//        oldCell.accessoryType = UITableViewCellAccessoryNone;
//    }
    
    UITableViewCell *cell = [_tableViewFriendPicker cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType != UITableViewCellAccessoryCheckmark) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        PersonNodeData *node = ((PersonNodeData *)[[_sortedValues objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]);
        [_pickerCategory.categoryArray addObject:node];
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
        PersonNodeData *node = ((PersonNodeData *)[[_sortedValues objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]);
        [_pickerCategory.categoryArray removeObject:node];
    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row >= [[_sortedValues objectAtIndex:indexPath.section] count]) {
        return;
    }
    
    UITableViewCell *cell = [_tableViewFriendPicker cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType != UITableViewCellAccessoryCheckmark) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        PersonNodeData *node = ((PersonNodeData *)[[_sortedValues objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]);
        [_pickerCategory.categoryArray addObject:node];
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
        PersonNodeData *node = ((PersonNodeData *)[[_sortedValues objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]);
        [_pickerCategory.categoryArray removeObject:node];
    }
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return _sortedKeys;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return [_sortedKeys indexOfObject:title];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [_sortedKeys objectAtIndex:section];
}

#pragma mark - UISearchBarDelegate

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    return YES;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self searchWithText:searchBar.text];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    _tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    [_tapGesture setNumberOfTapsRequired:1];
    [_tableViewFriendPicker addGestureRecognizer:_tapGesture];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    [_tableViewFriendPicker removeGestureRecognizer:_tapGesture];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self hideKeyboard];
    [self searchWithText:searchBar.text];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self hideKeyboard];
    [self searchWithText:@""];
}

@end
